<template>
    <a-form ref="formRef" @finish="handleFinish" :model="form" name="basic" :label-col="{ span: 8, }"
        :wrapper-col="{ span: 16 }" autocomplete="off">
        <a-row>

            <a-col :span="12">
                <a-form-item label="合同类型" name="subType">
                    <a-select :getPopupContainer="trigger => trigger.parentNode" :disabled="disabled" v-model:value="form.subType" style="width: 100%"
                        :options="contractType">
                    </a-select>
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="合同名称" name="name" :rules="[{ required: true }]">
                    <a-input :disabled="disabled" v-model:value="form.name" style="width: 100%" />
                </a-form-item>
            </a-col>


        </a-row>
        <a-row>
            <a-col :span="12">
                <a-form-item label="合同编码" name="code">
                    <a-input disabled v-model:value="form.code" style="width: 100%" />
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="项目名称" name="proId" :rules="[{ required: true }]">
                    <a-input-search :disabled="disabled" v-model:value="form.proName" style="width: 100%"
                        placeholder="选择的项目" @click="onSearch" @search="onSearch" />

                </a-form-item>
            </a-col>
        </a-row>
        <a-row>
            <a-col :span="12">
                <a-form-item label="甲方名称" name="partyA" :rules="[{ required: true }]">
                    <a-input :disabled="disabled" v-model:value="form.partyA" style="width: 100%"
                        @click="showCustomerSelect" />
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="甲方征信代码" name="partyACreditCode" :rules="[{ required: true }]">
                    <a-input :disabled="disabled" v-model:value="form.partyACreditCode" style="width: 100%" />
                </a-form-item>
            </a-col>
        </a-row>
        <a-row>
            <a-col :span="12">
                <a-form-item label="乙方名称" name="partyB" :rules="[{ required: true }]">
                    <a-input :disabled="disabled" v-model:value="form.partyB" style="width: 100%" />
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="乙方征信代码" name="partyBCreditCode" :rules="[{ required: true }]">
                    <a-input :disabled="disabled" v-model:value="form.partyBCreditCode" style="width: 100%" />
                </a-form-item>
            </a-col>
        </a-row>
        <a-row>
            <a-col :span="12">
                <a-form-item label="合同金额" name="amount" :rules="[{ required: true }]">
                    <a-input-number :precision="2" :min="0" :disabled="disabled" v-model:value="form.amount"
                        style="width: 100%" step="0.01" />
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="履约保证金" name="perBond" :rules="[{ required: true }]">
                    <a-input-number :precision="2" :min="0" :disabled="disabled" v-model:value="form.perBond"
                        style="width: 100%" :step="0.01" />
                </a-form-item>
            </a-col>
        </a-row>
        <a-row>
            <a-col :span="12">
                <a-form-item label="预计开工时间" name="expectedStartDate" :rules="[{ required: true }]">
                    <a-date-picker :getCalendarContainer="trigger => trigger.parentNode" :disabledDate="disabledDate" @change="change" valueFormat="YYYY-MM-DD hh:mm:ss"
                        :disabled="disabled" v-model:value="form.expectedStartDate" style="width: 100%" />
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="预计完工时间" name="expectedEndDate" :rules="[{ required: true }]">
                    <a-date-picker :getCalendarContainer="trigger => trigger.parentNode" :disabledDate="disabledEndDate" valueFormat="YYYY-MM-DD hh:mm:ss"
                        :disabled="disabled" v-model:value="form.expectedEndDate" style="width: 100%" />
                </a-form-item>
            </a-col>
        </a-row>
        <!-- <a-row>
            <a-col :span="12">
                <a-form-item label="合同有效期" name="expiryDate" :rules="[{ required: true }]">
                 
                    <a-date-picker :getCalendarContainer="trigger => trigger.parentNode" valueFormat="YYYY-MM-DD hh:mm:ss" :disabled="disabled"
                        v-model:value="form.expiryDate" style="width: 100%" />
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="通知方式" name="noticeType" :rules="[{ required: true }]">
                    <a-input-group compact> <a-form-item-rest>
                            <a-select :getPopupContainer="trigger => trigger.parentNode" :disabled="disabled" v-model:value="form.noticeType" style="width: 40%"
                                :options="noticeType">
                            </a-select>

                        </a-form-item-rest>
                        <a-input :disabled="disabled" v-model:value="form.notieAddr" style="width: 59%" />
                    </a-input-group>
                </a-form-item>
            </a-col>
        </a-row> -->
        <a-row>
            <a-col :span="12">
                <a-form-item label="付款方式" name="payType" :rules="[{ required: true }]">
                    <a-select :getPopupContainer="trigger => trigger.parentNode" :disabled="disabled" v-model:value="form.payType" style="width: 100%" :options="payType">

                    </a-select>
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="付款周期" name="payCycle" :rules="[{ required: true }]">
                    <a-select :getPopupContainer="trigger => trigger.parentNode" :disabled="disabled" v-model:value="form.payCycle" style="width: 100%"
                        :options="payCycle">
                    </a-select>
                </a-form-item>
            </a-col>
        </a-row>
        <a-row>
            <a-col :span="12">
                <a-form-item label="甲方联系人" name="partyAContacts" :rules="[{ required: true }]">
                    <a-input :disabled="disabled" v-model:value="form.partyAContacts" style="width: 100%" />
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="甲方联系人联系方式" name="partyAContactPhone" :rules="[{ required: true }]">
                    <a-input type="number" :disabled="disabled" v-model:value="form.partyAContactPhone" style="width: 100%" />
                </a-form-item>
            </a-col>
        </a-row>
        <a-row>
            <a-col :span="12">
                <a-form-item label="乙方联系人" name="partyBContacts" :rules="[{ required: true }]">
                    <a-input :disabled="disabled" v-model:value="form.partyBContacts" style="width: 100%" />
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="乙方联系人联系方式" name="partyBContactPhone" :rules="[{ required: true }]">
                    <a-input  type="number"  :disabled="disabled" v-model:value="form.partyBContactPhone" style="width: 100%" />
                </a-form-item>
            </a-col>
        </a-row>
        <a-row>
            <a-col :span="12">
                <a-form-item label="追加减是否有合同工程进度款同期支付" name="paySameTime">

                    <a-radio-group :disabled="disabled" v-model:value="form.paySameTime" style="height: 50px;">
                        <a-radio :value="'1'">是</a-radio>
                        <a-radio :value="'0'">否</a-radio>
                    </a-radio-group>
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="合同甲乙双方授权指定人是否明确" name="partyCertigierKnow">
                    <a-radio-group :disabled="disabled" v-model:value="form.partyCertigierKnow" style="height: 50px;">
                        <a-radio :value="'1'">是</a-radio>
                        <a-radio :value="'0'">否</a-radio>
                    </a-radio-group>
                </a-form-item>
            </a-col>
        </a-row>
        <a-row>

            <a-col :span="12">
                <a-form-item label="合同审核稿" name="contractDraft">
                    <fileUpload @uploadDone="uploadDone" :isShow="disabled" :files="form.files" ref="uploadRef2"
                        :type="2" :uploadNumber="4"></fileUpload>
                </a-form-item>
            </a-col>
        </a-row>


        <a-row>

            <a-col :span="24">
                <a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" label="追加减的方式和价格约定方式" name="method">
                    <a-textarea :disabled="disabled" v-model:value="form.method" style="width: 100%" />
                </a-form-item>
            </a-col>
        </a-row>
        <a-row>
            <a-col :span="24">
                <a-form-item :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" label="违约条款" name="breachClause">
                    <a-textarea :disabled="disabled" v-model:value="form.breachClause" style="width: 100%" />
                </a-form-item>
            </a-col>
        </a-row>
        <a-row>
            <a-col :span="12">
                <a-form-item label="质保期" name="warrantyPeriod">
                    <a-input-number :disabled="disabled" v-model:value="form.warrantyPeriod" style="width: 100%" />
                </a-form-item>
            </a-col>
            <!-- <a-col :span="12">
                <a-form-item label="乙方负责人" name="partyBDirector">
                    <a-input :disabled="disabled"  v-model:value="form.partyBDirector" style="width: 100%" />
                </a-form-item>
            </a-col> -->
        </a-row>


        <a-row>
            <a-col :span="24">
                <a-form-item label="备注" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" name="remark">
                    <a-textarea :disabled="disabled" v-model:value="form.remark" style="width: 100%" />
                </a-form-item>
            </a-col>
        </a-row>
        <a-row :gutter="16" class="mb-2" v-if="form.subType == 2">

            <a-col :span="6" class="text-left" style="font-weight: 600;">
                产品信息
            </a-col>
            <a-col :span="18" class="text-right" v-if="!disabled">
                <a-button class="ml-2" @click="onShowProductSelect" type="primary">新增一条</a-button>
            </a-col>
        </a-row>

        <a-row :gutter="16" v-if="form.subType == 2">
            <a-col :span="24">
                <a-table :dataSource="form.productList" bordered :scroll="{ x: 1000, }" :columns="columns"
                    :pagination="false" class="mb-2">
                    <template #bodyCell="{ column, record, index }">
                        <template v-if="column.key === 'index'">
                            {{ index + 1 }}
                        </template>

                        <template v-if="column.key === 'unitPrice'">
                            <a-input-number :min="0" :disabled="disabled" :precision="2"
                                v-model:value="record.unitPrice"></a-input-number>
                        </template>
                        <template v-if="column.key === 'quantity'">
                            <a-input-number :min="0" :disabled="disabled"
                                v-model:value="record.quantity"></a-input-number>
                        </template>
                        <template v-if="column.key === 'tax'">
                            <a-input-number :min="0" :max="1" :disabled="disabled" :precision="2"
                                v-model:value="record.tax"></a-input-number>
                        </template>
                        <template v-if="column.key === 'taxAmount'">
                            {{ record.unitPrice && record.quantity ? (record.unitPrice * record.quantity) : 0 }}
                            <!-- <a-input-number  :disabled="disabled" :precision="2" v-model:value="record.taxAmount"></a-input-number> -->
                        </template>
                        <template v-if="column.key === 'notaxAmount'">
                            <!-- 含税金额-含税金额*税率 -->
                            {{ record.unitPrice && record.quantity && record.tax ?
        (record.unitPrice * record.quantity) - ((record.unitPrice * record.quantity) * record.tax) :
        0 }}
                        </template>
                        <template v-if="column.key === 'control'">
                            <a-popconfirm title="确定删除此数据源？" @confirm="remove(index)">
                                <a-button type="link" danger size="small">删除</a-button>
                            </a-popconfirm>
                        </template>
                    </template>
                </a-table>
            </a-col>
        </a-row>
        <div style="margin-top: 15px" v-if="form.subType == 2">
            <span style="color: #333; font-size: 16px; font-weight: 600">合计</span>
        </div>
        <a-row :gutter="24" style="margin-bottom: 50px; margin-top: 15px; margin-left: 20px" v-if="form.subType == 2">
            <a-col :span="8">
                <div style="margin-right: 12px; display: inline-block">
                    <span>销售数量:</span>
                </div>
                <a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="saleNum" />
            </a-col>
            <a-col :span="8">
                <div style="margin-right: 12px; display: inline-block">
                    <span>不含税总金额</span>
                </div>
                <a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="notaxAmount" />
            </a-col>
            <a-col :span="8">
                <div style="margin-right: 12px; display: inline-block">
                    <span>含税总金额</span>
                </div>
                <a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="taxAmount" />
            </a-col>

        </a-row>
        <system :value="form"></system>
        <projectSelection ref="proSelect" @onClose="prSelectOk" :value="form.proSelectRecords" />
        <customerSelect ref="customerSelectRef" @OnClose="customerSelectOk" :value="form.customSelectRecords">
        </customerSelect>
        <productSelection ref="productSelect" @onClose="productSelectOk" />
    </a-form>
</template>

<script setup>
import api from '@/api/contract/revenueContract/index'
import projectSelection from '@/components/pm/projectSelection.vue'
import productSelection from '@/components/pm/productSelection.vue'
import customerSelect from '@/components/pm/customSelection.vue'
import system from '@/components/Task/system.vue'
import fileUpload from '@/components/JqUpload/index.vue'
import { noticeType, contractType, payType, payCycle } from '@/utils/constants.js'
import dayjs from 'dayjs';
const customerSelectRef = ref()
const showCustomerSelect = () => {
    customerSelectRef.value.show("")
}
const customerSelectOk = (data) => {
    form.value.partyA = data[0].custName
    form.value.partyAId = data[0].id
    form.value.partyACreditCode = data[0].custCode

    form.value.customSelectRecords = data
}


const disabledDate = current => {
    return current && current < dayjs().endOf('day');
};
const disabledEndDate = (current) => {
    const start = form.value.expectedStartDate
    if (!start) {
        return current && current < dayjs().endOf('day');
    }
    return current.valueOf() <= dayjs(start).endOf('day'); // 结束日期必须大于开始日期
}
const change = () => {
    const start = form.value.expectedStartDate
    const end = form.value.expectedEndDate
    if (dayjs(start) > dayjs(end)) {
        form.value.expectedEndDate = null
    }
}

const form = ref({})
const formRef = ref()
const columns = [
    {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        width: 80,
        align: "center",
    },
    {
        title: '编号',
        dataIndex: 'productNo',
        key: 'productNo',
        width: 80,
        align: "center",
        ellipsis: true
    },
    {
        title: '产品名称',
        dataIndex: 'product',
        key: 'product',
        width: 120,
        align: "center",
        ellipsis: true
    },
    {
        title: '单位',
        dataIndex: 'productUnit',
        key: 'productUnit',
        width: 80,
        align: "center",
        ellipsis: true
    },
    {
        title: '规格型号',
        dataIndex: 'productSpec',
        key: 'productSpec',
        width: 100,
        align: "center",
        ellipsis: true
    },


    {
        title: '单价',
        dataIndex: 'unitPrice',
        key: 'unitPrice',
        width: 110,
        align: "center",
    },
    {
        title: '数量',
        dataIndex: 'quantity',
        key: 'quantity',
        width: 110,
        align: "center",
    },
    {
        title: '税率',
        dataIndex: 'tax',
        key: 'tax',
        width: 110,
        align: "center",
    },
    {
        title: '不含税金额',
        dataIndex: 'notaxAmount',
        key: 'notaxAmount',
        width: 120,
        align: "center",
    },
    {
        title: '含税价格',
        dataIndex: 'taxAmount',
        key: 'taxAmount',
        width: 100,
        align: "center",
    },

    {
        title: '操作',
        dataIndex: 'control',
        key: 'control',
        width: 80,
        align: "center",
        fixed: "right"
    },
]

const saleNum = computed(() => {
    var quantity = 0;
    form.value.productList?.forEach(record => {
        if (record.quantity) {
            quantity += record.quantity
        }
    });
    return quantity
})
const taxAmount = computed(() => {
    var amount = 0;
    form.value.productList?.forEach(record => {
        if (record.unitPrice && record.quantity) {
            amount += record.unitPrice * record.quantity
            record.taxAmount = record.unitPrice * record.quantity
        }

    });
    return amount
})

const notaxAmount = computed(() => {
    var amount = 0;
    form.value.productList?.forEach(record => {
        if (record.unitPrice && record.quantity && record.tax) {
            amount += (record.unitPrice * record.quantity) - ((record.unitPrice * record.quantity) * record.tax)
            record.notaxAmount = (record.unitPrice * record.quantity) - ((record.unitPrice * record.quantity) * record.tax)
        }

    });
    return amount
})
const remove = (index) => {
    form.value.productList.splice(index, 1)
}
const uploadDone = (result) => {
    form.value.files = result
}
const proSelect = ref()
const onSearch = () => {
    proSelect.value.show()
}
const prSelectOk = (selectedRowKeys, selectRecords) => {
    console.log("项目选择ok")
    form.value.proId = selectRecords[0].id
    form.value.proName = selectRecords[0].name
    form.value.proSelectRecords = selectRecords
}

const productSelect = ref()
const onShowProductSelect = () => {
    productSelect.value.show()
}
const productSelectOk = (selectedRowKeys, selectRecords) => {
    console.log("产品选择ok ", selectedRowKeys, selectRecords)
    if (!form.value.productList) {
        form.value.productList = []
    }
    selectRecords.forEach((item, index) => {
        item.productId = item.id
        if (!form.value.productList.find(x => x.productId == item.id)) {
            form.value.productList.push(item)
        }
    })

}


const submit = () => {
    formRef.value.validate().then(() => {
        handleFinish(form.value)
    }).catch((err) => {

    });
}
const handleFinish = (values) => {

    console.log("handleFinish", values);
    if (!form.value.id) {
        api.add(values).then(() => {
            onClose(true);
        })
    } else {
        values.id = form.value.id;
        api.edit(values).then(() => {
            onClose(true);
        })
    }
};
const isEdit = ref(false)
const show = (record) => {
    if (record) {
        form.value = { ...record }
        if (form.value.name) {
            columns.splice(columns.length - 1, 1)
        }
    }
}


const props = defineProps({
    value: {
        type: Object,
        default: () => { }
    },
    disabled: {
        type: Boolean,
        default: () => false
    }
})

watch(
    () => props.value,
    (newVal, oldVal) => {
        if (newVal) {
            form.value = { ...newVal }
            if (form.value.name) {
                columns.splice(columns.length - 1, 1)
            }
        }
    },
    { deep: true, immediate: true }
)

const getData = () => {
    return new Promise((resolve, reject) => {
        formRef.value.validate().then(() => {
            form.value.flowCode = "FLW_CONTRACT_IN"
            resolve(form.value)
        }).catch((err) => {
            reject(err)
        });
    })
}
// 重置
const resetForm = () => {
    formRef.value.resetFields()
}
defineExpose({
    getData,
    resetForm,
    show
})

</script>

<style>
label {
    white-space: normal;
}

.ant-form-item-label>label {
    min-height: 32px !important;
    height: auto;
}
</style>
